﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Transactions;

public partial class Main_Master_FinYear : System.Web.UI.Page
{
    Datautility du = new Datautility();
    protected void Page_Load(object sender, EventArgs e)
    {
         if (Session["userid"] == null)
         {            
            Response.Redirect("~/SessionExpired.aspx");
         }
          
         if (!IsPostBack)
         {
             _BindGridView();
             TxtCurrentDate.Text = Session["CURRENTDATE"].ToString();
             hidCurrentFinyear.Value = Session["FINYEAR"].ToString();
             AccountSettings.setMinMaxDate(form1);
         }
         hidCurrentDate.Value = Session["CURRENTDATE"].ToString();
    }  

    private DataTable _GetWorkingDate()
    {
        DataTable DTWorkingDate = new DataTable();
        DTWorkingDate.Columns.Add("FinDate",typeof(DateTime));
        DTWorkingDate.Columns.Add("FinYear", typeof(string));
        DTWorkingDate.Columns.Add("Fin_Year", typeof(string));
        string strSql = "Select * from MAS_FINYEAR";
        DataTable DT= du.getdata(strSql);
        if (DT.Rows.Count > 0)
        {
            for (int i = 0; i < DT.Rows.Count; i++)
            {
                if (DT.Rows[i]["FINYEAR"].ToString() != string.Empty)
                {
                    DataRow DRRow = DTWorkingDate.NewRow();
                    string strDate = "01/04/" + DT.Rows[i]["FINYEAR"].ToString();
                    string strFinyear = DT.Rows[i]["FINYEAR"].ToString();
                    string strFin_year = DT.Rows[i]["FINYEAR"].ToString() + "-" + (Convert.ToDouble(DT.Rows[i]["FINYEAR"].ToString()) + 1).ToString();
                    DRRow["FinDate"] =Convert.ToDateTime(strDate);
                    DRRow["FinYear"] = strFinyear;
                    DRRow["Fin_Year"] = strFin_year;
                    DTWorkingDate.Rows.Add(DRRow);
                }
            }
        }
        return DTWorkingDate;
    }
    private void _BindGridView()
    {
        DataTable DT = _GetWorkingDate();
        Grdfinyear.DataSource = DT;
        Grdfinyear.DataBind();
    }
    protected void Grdfinyear_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {          
            Label LblFinyear = (Label)e.Row.FindControl("LblFinDate");
            e.Row.Attributes.Add("onclick", "Finyear('" + LblFinyear.ClientID + "');");

            string strDataKey = Grdfinyear.DataKeys[e.Row.RowIndex].Value.ToString();
            string strsql = "SELECT WORKINGDATE FROM ACC_USERWORKINGDATE WHERE USERID='" + Session["userid"].ToString() + "'";
            DataTable DTWorkingDate = du.getdata(strsql);
            if (DTWorkingDate.Rows.Count > 0)
            {
                string[] str = string.Format("{0:dd/MM/yyyy}", DTWorkingDate.Rows[0]["WORKINGDATE"]).Split('/');
                string strMonth = str[1];
                string strYear = str[2];
                strsql = "SELECT FINYEAR FROM ACC_MONTHYEAR WHERE MONTHVALUE='" + strMonth + "' AND YEARVALUE='" + strYear + "'";
                DataTable DTFinYear = du.getdata(strsql);                
                if (DTFinYear.Rows.Count > 0)
                {
                    if (strDataKey == DTFinYear.Rows[0]["FINYEAR"].ToString())
                    {
                       ((Label)e.Row.FindControl("LblFinDate")).Text = string.Format("{0:dd/MM/yyyy}", DTWorkingDate.Rows[0]["WORKINGDATE"]).ToString();
                    }
                }
            }
        }
    }
    private string _GetFinancialYear(string strDate)
    {
        string strFinYear = string.Empty;
        if (strDate != string.Empty)
        {
            string[] str = strDate.Split('/');            
            string strMonth = str[1];
            string strYear = str[2];
            if (Convert.ToInt32(strMonth)>= 04 && Convert.ToInt32(strMonth) <= 12)
            {
                strFinYear = strYear;
            }
            else if (Convert.ToInt32(strMonth) >= 1 && Convert.ToInt32(strMonth) < 4)
            {
                strFinYear = (Convert.ToInt32(strYear) - 1).ToString();
            }
        }
        return strFinYear;
    }
    private string  _CurrentYear()
    {
        string strMsg = string.Empty;
        string strFinYear = _GetFinancialYear(TxtCurrentDate.Text);
        string strCurrentDate = string.Empty;
        if (TxtCurrentDate.Text != string.Empty)
        {
            string[] str = TxtCurrentDate.Text.Split('/');
            strCurrentDate = str[1] + "/" + str[0] + "/" + str[2];
        }
        if (strCurrentDate != string.Empty)
        {           
            SqlParameter[] sparam2 ={
                                     new SqlParameter("@USERID",Session["userid"].ToString()),
                                     new SqlParameter("@WORKINGDATE",strCurrentDate)
                                    };
            du.executeprocedure("USP_ACC_SaveUserWorkingDate", sparam2);
            Session["CURRENTDATE"] = TxtCurrentDate.Text;
            Session["FINYEAR"] = strFinYear;
            strMsg = "Update";
        }
        return strMsg;

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                string strMsg = _CurrentYear();
                scope.Complete();
                if (strMsg == "Update")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "CloseWindow();", true);
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
    protected void btnCreatefinyear_Click(object sender, EventArgs e)
    {
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                string strFinYear = _GetFinancialYear(TxtCurrentDate.Text);
                string strCurrentDate = string.Empty;
                if (TxtCurrentDate.Text != string.Empty)
                {
                    string[] str = TxtCurrentDate.Text.Split('/');
                    strCurrentDate = str[1] + "/" + str[0] + "/" + str[2];
                }
                if (strFinYear != string.Empty)
                {
                    string strPrevFinyear = string.Empty;
                    string strSql = "SELECT MAX(FINYEAR)AS MAXFINYEAR FROM MAS_FINYEAR";
                    DataTable DTFinyear = du.getdata(strSql);
                    if (DTFinyear.Rows.Count > 0 && DTFinyear.Rows[0]["MAXFINYEAR"].ToString() != string.Empty)
                    {
                        strPrevFinyear = DTFinyear.Rows[0]["MAXFINYEAR"].ToString();
                    }

                    string strStartDate = strCurrentDate;
                    string strEndDate = "03/31/" + (Convert.ToInt32(strFinYear) + 1).ToString();

                    SqlParameter[] sparam ={
                                               new SqlParameter("@FINYEAR",strFinYear)
                                           };
                    int result = du.executeprocedure("USP_ACC_CreateNewFinancialYear", sparam);
                    SqlParameter[] sparam1 ={
                                                new SqlParameter("@MONTHID","0"),
                                                new SqlParameter("@STARTDATE",strStartDate),
                                                new SqlParameter("@ENDDATE",strEndDate)

                                            };
                    du.executeprocedure("USP_ACC_CreateDefaultMonthAndYearValues", sparam1);
                    if (result > 0)
                    {
                        if (strPrevFinyear != string.Empty)
                        {
                            SqlParameter[] sparam2 ={
                                            new SqlParameter("@PREVFINYEAR",strPrevFinyear),
                                            new SqlParameter("@NEWFINYEAR",strFinYear)
                                        };
                            du.executeprocedure("USP_ACC_InsertAccountingTranSettingDetails", sparam2);
                        }
                    }
                }
                scope.Complete();
            }
            _BindGridView();
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
        
    }
}
